package com.bstek.ureport.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.bstek.ureport.definition.datasource.ConfigPropUtil;
import com.google.zxing.datamatrix.encoder.SymbolShapeHint;
import com.mchange.v2.c3p0.ComboPooledDataSource;


public class UreportDBConnectionPoolUtils {

	// 服务名 连接池映射
	private static Map<String, ComboPooledDataSource> mapping = new HashMap<String, ComboPooledDataSource>();
	
	// 单个服务的初始链接数量
	private static int oneServerInitalPoolSize = 1;
	// 单个服务的最大链接数量 
	private static int oneServerMaxPoolSize = 1;
	// 每个服务的连接池最小连接数量
	private static int oneServerMinPoolSize = 1;
	// 连接不活动后多久断开连接
	private static int oneServerMaxIdleTime = 10;
	
//	private static Connection mainDatabaseConn;
	
	static {
		init();
	}
	
	/**
	 * 初始化配置属性和一个主数据库的链接
	 */
	private static void init() {
		String str;
		str = ConfigPropUtil.getProperty("reportDbConnectionPool.oneServerInitalPoolSize");
		if(null != str && !"".equals(str)) {
			oneServerInitalPoolSize = Integer.parseInt(str);
		}
		str = ConfigPropUtil.getProperty("reportDbConnectionPool.oneServerMaxPoolSize");
		if(null != str && !"".equals(str)) {
			oneServerMaxPoolSize = Integer.parseInt(str);
		}
		str = ConfigPropUtil.getProperty("reportDbConnectionPool.oneServerMinPoolSize");
		if(null != str && !"".equals(str)) {
			oneServerMinPoolSize = Integer.parseInt(str);
		}
		str = ConfigPropUtil.getProperty("reportDbConnectionPool.oneServerMaxIdleTime");
		if(null != str && !"".equals(str)) {
			oneServerMaxIdleTime = Integer.parseInt(str);
		}
		
		String username = ConfigPropUtil.getProperty("jdbc.username");
		String password = ConfigPropUtil.getProperty("jdbc.password");
		String driver = ConfigPropUtil.getProperty("jdbc.driver");
		String url = ConfigPropUtil.getProperty("jdbc.url");
		
		try {
			ComboPooledDataSource pool = new ComboPooledDataSource();
			pool.setInitialPoolSize(oneServerInitalPoolSize);
			pool.setMaxPoolSize(oneServerMaxPoolSize);
			pool.setMaxIdleTime(oneServerMaxIdleTime);
			pool.setMinPoolSize(oneServerMinPoolSize);
			pool.setDriverClass(driver);
			pool.setJdbcUrl(url);
			pool.setUser(username);
			pool.setPassword(password);
			mapping.put("mainDatabase", pool);
		} catch (Exception e) {
			throw new RuntimeException("ureport数据库连接初始化失败");
		}
	}
	
	/**
	 * 根据服务的名称获取数据库连接
	 * @param serverName
	 * @return
	 */
	public static Connection getConnection(String serverName) {
		if(null == serverName) {
			return null;
		}
		try {
			if(!mapping.containsKey(serverName)) {
				if(addPool(serverName)) {
					ComboPooledDataSource pool = mapping.get(serverName);
					return pool.getConnection();
				}
			}else {
				ComboPooledDataSource pool = mapping.get(serverName);
				return pool.getConnection();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	/**
	 * 连接池列表中新增链接池
	 * @param serverName
	 */
	private static boolean addPool(String serverName) {
		try {
			ComboPooledDataSource mainDatabase = mapping.get("mainDatabase");
			Connection connection = null;
			if(null == mainDatabase || null == (connection = mainDatabase.getConnection())) {
				return false;
			}
			String sql = "SELECT id, dbdriver, dbip, dbname, dbport, dbpwd, dbuser FROM pt_dbinfo WHERE active = ? AND ismain = ? AND id = ?;";
			PreparedStatement statement = connection.prepareStatement(sql);
			statement.setInt(1, 1);
			statement.setInt(2, 1);
			statement.setString(3, serverName);
			ResultSet resultSet = statement.executeQuery();
			if(resultSet.next()) {
				String username = resultSet.getString("dbuser");
				String password = resultSet.getString("dbpwd");
				String driver = resultSet.getString("dbdriver");
				String url = "jdbc:mysql://"
						+ resultSet.getString("dbip") 
						+ ":"
						+ resultSet.getString("dbport")
						+ "/"
						+ resultSet.getString("dbname")
						+ "?characterEncoding=UTF-8&useSSL=false&createDatabaseIfNotExist=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
				Class.forName(driver);
				Connection conn=DriverManager.getConnection(url, username, password);
				
				if(null == conn) {
					throw new RuntimeException("数据库连接池创建失败，服务名：" + serverName);
				}
				conn.close();
				ComboPooledDataSource pool = new ComboPooledDataSource();
				pool.setInitialPoolSize(oneServerInitalPoolSize);
				pool.setMaxPoolSize(oneServerMaxPoolSize);
				pool.setMaxIdleTime(oneServerMaxIdleTime);
				pool.setMinPoolSize(oneServerMinPoolSize);
				pool.setDriverClass(driver);
				pool.setJdbcUrl(url);
				pool.setUser(username);
				pool.setPassword(password);
				mapping.put(serverName, pool);
			}else {
				throw new RuntimeException("查询不到这个服务的数据库连接：" + serverName);
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return true;
	}

}
